<template>
  <view class="benben-image-upload" @click="clickEvent">
    <slot />
  </view>
</template>
<script>
import UploadImage from '@/common/utils/upload-image.js'
import { syncUniApi } from '@/common/utils/utils.js'
/*  @property  {String} imgiId            图片id    选填填项
      @property  {String} path            图片路径    必填项
      @property  {Boolean} isCropping     是否开启裁剪模式   false
      @property  {Boolean} isShowClean     是否显示删除图标   false
      @property  {function} update-success  上传成功回调
      */
// isShowClean 为true 时  slot 中必须有一个data-type="clean"的 text 标签
// <text  data-type="clean" class='fu-iconfont2 position-absolute'>&#xE8E7;</text>
export default {
  name: 'benben-image-upload',
  props: {
    isShowClean: {
      type: [Boolean],
      default: false,
    },
    isCropping: {
      type: [Boolean],
      default: false,
    },
    uploadLoading: {
      type: [Boolean],
      default: false,
    },
    path: {
      type: String,
      default: '',
    },
    imgiId: {
      type: [String, Number],
      default: '',
    },
    imgFrom: {
      type: String,
      default: 'album',
    },
    // croppingTypes裁切模式   auto（不设尺寸）、settled（固定尺寸）
    croppingTypes: {
      type: [String],
      default: 'settled',
    },
    croppingWidth: {
      type: [Number, String],
      default: 200,
    },
    croppingHeight: {
      type: [Number, String],
      default: 200,
    },
    atype: {
      type: [String],
      default: 'upload',
    },
  },
  data: () => ({}),
  computed: {},
  //监听imgIds
  watch: {},
  methods: {
    // —————————————————————— 签名组件 start ——————————————————————
    onSign() {
      uni.navigateTo({
        url: '/pages/benben-built-in/image-sign/image-sign',
        success: () => {
          uni.$once('getSignImg', (e) => {
            let tempFiles = [
              {
                name: 'sign.png',
                path: e.base64,
              },
            ]
            this.$emit('update:upload-loading', true)
            new UploadImage(tempFiles, {
              complete: (res) => {
                this.uploading = false
                this.$emit('update:img-id', res[0].id)
                this.$emit('update:path', res[0].path)
                this.$emit('update:upload-loading', false)
                this.$emit('update-success', res[0])
                this.imageCroppingCuccess()
              },
            })
          })
        },
      })
    },
    // —————————————————————— 签名组件 start ——————————————————————
    delImage() {
      this.$emit('update:img-id', '')
      this.$emit('update:path', '')
    },
    clickEvent(e) {
      if (this.atype == 'sign') {
        this.onSign()
        return
      }
      if (this.isShowClean && this.path) {
        uni.previewImage({
          current: this.path,
          urls: [this.path],
        })
        return
      }
      if (!this.isCropping) this.soloChooseImage()
      else this.croppingUploadImage()
    },
    UploadImage(tempFiles) {
      this.$emit('update:upload-loading', true)
      // 开始上传
      this.uploading = true
      new UploadImage(tempFiles, {
        complete: (res) => {
          this.uploading = false
          this.$emit('update:img-id', res[0].id)
          this.$emit('update:path', res[0].path)
          this.$emit('update:upload-loading', false)
          this.$emit('update-success', res[0])
        },
      })
    },
    async soloChooseImage() {
      if (this.uploading) return
      // 从相册中选择图片
      let sArr = ['album']
      if (this.imgFrom == 'all') sArr = ['album', 'camera']
      if (this.imgFrom == 'camera') sArr = ['camera']
      let FilesRes = await syncUniApi('chooseImage', {
        count: 1, // 默认3
        sourceType: sArr,
        sizeType: ['original', 'compressed'],
      })
      this.UploadImage(FilesRes.tempFiles)
    },
    imageCroppingCuccess() {
      uni.$once('image-cropping-success', (file) => {
        if (!file) return
        this.UploadImage([file])
      })
    },
    //裁剪图片上传
    croppingUploadImage(id, path, obj, obj1, fnName = false) {
      let itemList = this.path
        ? [global.i18n.t('修改头像'), global.i18n.t('拍照'), global.i18n.t('从手机相册选择')]
        : [global.i18n.t('拍照'), global.i18n.t('从手机相册选择')]
      uni.showActionSheet({
        itemList: itemList,
        success: async (res) => {
          if (res.tapIndex == 0 && this.path) {
            uni.navigateTo({
              url: `/pages/benben-built-in/image-cropping/image-cropping?croppingTypes=${this.croppingTypes}&rectWidth=${this.croppingWidth}&rectHeight=${this.croppingHeight}&myImgUrl=${this.path}`,
              animationDuration: 0,
            })
            this.imageCroppingCuccess()
            return
          }
          let sourceType = ['camera']
          if ((res.tapIndex == 1 && this.path) || (res.tapIndex == 0 && !this.path)) {
            sourceType = ['camera']
          }
          if ((res.tapIndex == 2 && this.path) || (res.tapIndex == 1 && !this.path)) {
            sourceType = ['album']
          }
          let FilesRes = await syncUniApi('chooseImage', {
            count: 1,
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType, // 可以指定来源是相册还是相机，默认二者都有
          })
          // 跳转到图片裁切页面
          uni.navigateTo({
            url: `/pages/benben-built-in/image-cropping/image-cropping?croppingTypes=${this.croppingTypes}&rectWidth=${this.croppingWidth}&rectHeight=${this.croppingHeight}&fileType=${FilesRes.tempFiles[0].type}&myImgUrl=${FilesRes.tempFilePaths[0]}`,
            animationDuration: 0,
          })
          this.imageCroppingCuccess()
        },
        fail: function (res) {
          console.log(res.errMsg)
        },
      })
    },
  },
  // 组件周期函数--监听组件挂载完毕
  mounted() {},
  // 组件周期函数--监听组件数据更新之前
  beforeUpdate() {},
  // 组件周期函数--监听组件数据更新之后
  updated() {},
  // 组件周期函数--监听组件激活(显示)
  activated() {},
  // 组件周期函数--监听组件停用(隐藏)
  deactivated() {},
  // 组件周期函数--监听组件销毁之前
  beforeDestroy() {},
}
</script>
<style lang="scss">
.benben-image-upload {
  line-height: initial;
}
</style>
